{% extends 'base.html' %} {% comment %} 继承基础模板 {% endcomment %}
{% block title %}{% if is_update %}编辑错题{% else %}添加新错题{% endif %}{% endblock %} {% comment %} 页面标题，根据是否为更新操作动态显示 {% endcomment %}

{% block extra_css %} {% comment %} 额外的CSS样式块 {% endcomment %}
<style>
    .form-group {
        margin-bottom: 1.5rem;  /* 表单组底部边距 */
    }
    .error-feedback {
        color: #dc3545;  /* 错误提示颜色 */
        font-size: 0.875em;  /* 错误提示字体大小 */
        margin-top: 0.25rem;  /* 错误提示顶部边距 */
    }
    #preview-question, #preview-answer {
        border: 1px solid #ced4da;  /* 预览区域边框 */
        padding: 1rem;  /* 预览区域内边距 */
        border-radius: 0.375rem;  /* 预览区域圆角 */
        min-height: 100px;  /* 预览区域最小高度 */
        margin-top: 0.5rem;  /* 预览区域顶部边距 */
        background-color: #f8f9fa;  /* 预览区域背景色 */
        transition: all 0.3s ease;  /* 预览区域过渡效果 */
    }
    #preview-question:hover, #preview-answer:hover {
        box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.1);  /* 预览区域悬停效果 */
    }
    .btn-primary {
        transition: all 0.3s ease;  /* 主按钮过渡效果 */
    }
    .btn-primary:hover {
        transform: translateY(-2px);  /* 主按钮悬停上移效果 */
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);  /* 主按钮悬停阴影效果 */
    }
    .form-control:focus {
        border-color: #86b7fe;  /* 表单控件聚焦边框颜色 */
        box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);  /* 表单控件聚焦阴影效果 */
    }
    .card {
        transition: all 0.3s ease;  /* 卡片过渡效果 */
    }
    .card:hover {
        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);  /* 卡片悬停阴影效果 */
    }
</style>
{% endblock %}

 {{ form.media }}  <!-- 加载 CKEditor 富文本编辑器资源 -->
    <!-- 使用最新稳定版本的MathJax，用于渲染数学公式 -->
    <script src="https://cdn.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-mml-chtml.js"></script>
    <script>
        // 只在MathJax未配置时才进行配置，避免重复配置
        if (!window.MathJax) {
            window.MathJax = {
                tex: {
                    inlineMath: [['$', '$'], ['\\(', '\\)']],  /* 行内公式分隔符 */
                    displayMath: [['$$', '$$'], ['\\[', '\\]']],  /* 块级公式分隔符 */
                    processEscapes: true,  /* 允许转义字符 */
                    packages: {'[+]': ['noerrors']}  /* 添加noerrors包，避免公式错误时显示异常 */
                },
                svg: {
                    fontCache: 'global'  /* 全局字体缓存，提高性能 */
                },
                startup: {
                    typeset: false  /* 禁用自动排版，我们将手动触发 */
                }
            };
        }
    </script>

{% block content %} {% comment %} 页面主要内容块 {% endcomment %}
 <form method="post" enctype="multipart/form-data"> {% comment %} 主表单，支持文件上传 {% endcomment %}
    {% csrf_token %} {% comment %} Django CSRF保护令牌 {% endcomment %}
   

<div class="container mt-5 mb-8"> {% comment %} 容器，设置上下边距 {% endcomment %}
    <div class="card shadow-md rounded-lg overflow-hidden border-0"> {% comment %} 卡片容器，带阴影和圆角 {% endcomment %}
        <div class="card-header bg-gradient-to-r from-primary to-blue-600 text-white py-4"> {% comment %} 卡片头部，渐变背景 {% endcomment %}
            <h4 class="mb-0 font-bold">{% if is_update %}<i class="bi bi-pencil me-2" style="color: black;"></i><span style="color: black;">编辑错题</span>{% else %}<i class="bi bi-plus-circle me-2" style="color: black;"></i><span style="color: black;">添加新错题</span>{% endif %}</h4> {% comment %} 卡片标题，根据是否为更新操作动态显示 {% endcomment %}
        </div>
        <div class="card-body p-6"> {% comment %} 卡片主体，设置内边距 {% endcomment %}
            {% if form.errors %} {% comment %} 表单错误提示 {% endcomment %}
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <strong>保存失败!</strong> 请检查以下字段并修正错误。
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
            {% endif %}

            <form method="post" id="mistake-form"> {% comment %} 错题表单 {% endcomment %}
                {% csrf_token %} {% comment %} Django CSRF保护令牌 {% endcomment %}
                <div class="row"> {% comment %} 第一行表单控件 {% endcomment %}
                    <div class="form-group col-md-3"> {% comment %} 学科选择 {% endcomment %}
                        <label for="subject">学科 <span class="text-danger">*</span></label>
                        <select class="form-control {% if form.subject.errors %}is-invalid{% endif %}" id="subject" name="subject" required>
                            <option value="">选择学科</option>
                            {% for subject in subjects %}
                            <option value="{{ subject.id }}" {% if initial_subject and subject.id == initial_subject.id %}selected{% endif %}>{{ subject.name }}</option>
                            {% endfor %}
                        </select>
                        {% if form.subject.errors %}
                        <div class="error-feedback">{{ form.subject.errors }}</div>
                        {% endif %}
                    </div>
                    <div class="form-group col-md-3"> {% comment %} 章节选择 {% endcomment %}
                        <label for="chapter">章节 <span class="text-danger">*</span></label>
                        <select class="form-control {% if form.chapter.errors %}is-invalid{% endif %}" id="chapter" name="chapter" required disabled>
                            <option value="">选择章节</option>
                        </select>
                        {% if form.chapter.errors %}
                        <div class="error-feedback">{{ form.chapter.errors }}</div>
                        {% endif %}
                    </div>
                    <div class="form-group col-md-3"> {% comment %} 知识点选择 {% endcomment %}
                        <label for="knowledge_point">知识点 <span class="text-danger">*</span></label>
                        <select class="form-control {% if form.knowledge_point.errors %}is-invalid{% endif %}" id="knowledge_point" name="knowledge_point" required disabled>
                            <option value="">选择知识点</option>
                        </select>
                        {% if form.knowledge_point.errors %}
                        <div class="error-feedback">{{ form.knowledge_point.errors }}</div>
                        {% endif %}
                    </div>
                    <div class="form-group col-md-3"> {% comment %} 难度评级选择 {% endcomment %}
                        <label for="star_rating">难度评级 <span class="text-danger">*</span></label>
                        <select class="form-control {% if form.star_rating.errors %}is-invalid{% endif %}" id="star_rating" name="star_rating" required>
                            <option value="1">1星 (简单)</option>
                            <option value="2">2星 (较简单)</option>
                            <option value="3" selected>3星 (中等)</option>
                            <option value="4">4星 (较难)</option>
                            <option value="5">5星 (困难)</option>
                        </select>
                        {% if form.star_rating.errors %}
                        <div class="error-feedback">{{ form.star_rating.errors }}</div>
                        {% endif %}
                    </div>
                </div>

                <div class="form-group"> {% comment %} 标题输入框 {% endcomment %}
                    <label for="title">标题 <span class="text-danger">*</span></label>
                    <input type="text" class="form-control {% if form.title.errors %}is-invalid{% endif %}" id="title" name="title" value="{{ form.title.value|default:'' }}" required>
                    {% if form.title.errors %}
                    <div class="error-feedback">{{ form.title.errors }}</div>
                    {% endif %}
                </div>

                <div class="row align-items-stretch"> {% comment %} 问题描述行，包含编辑器和预览 {% endcomment %}
                    <div class="form-group col-md-7" id="question-group"> {% comment %} 问题描述编辑器 {% endcomment %}
                        <label for="question">问题描述 <span class="text-danger">*</span></label>
                        <textarea class="form-control ckeditor {% if form.question.errors %}is-invalid{% endif %}" id="question" name="question" rows="4" required>{{ form.question.value|default:'' }}</textarea>
                        {% if form.question.errors %}
                        <div class="error-feedback">{{ form.question.errors }}</div>
                        {% endif %}
                        <div id="question-upload" class="mt-3"> {% comment %} 问题图片上传区域 {% endcomment %}
                            <label class="btn btn-outline-secondary btn-sm" for="question-image-upload" id="question-image-upload-btn">
                                <input type="text" id="question-image-url" hidden>  {% comment %} 隐藏的图片URL输入框 {% endcomment %}
                                <i class="bi bi-upload me-1"></i> 上传图片 
                            </label>
                            <label class="btn btn-outline-secondary btn-sm" for="question-image-analysis" id="question-image-analysis-btn">
                                <i class="bi bi-upload me-1"></i> 用豆包获取内容 
                            </label>
                            <div class="form-check form-check-inline"> {% comment %} 自动生成答案复选框 {% endcomment %}
                                <input class="form-check-input" type="checkbox" id="answer-image-check" checked>
                                <label class="form-check-label" for="answer-image-check">
                                    <i class="bi bi-upload me-1"></i> 自动生成答案
                                </label>
                            </div>
                            <input type="file" id="question-image-upload" name="question_image" accept="image/*" class="d-none"> {% comment %} 隐藏的文件上传控件 {% endcomment %}
                            <div id="question-image-preview" class="mt-2"></div> {% comment %} 图片预览区域 {% endcomment %}
                        </div>
                    </div>
                    <div class="form-group col-md-5 ms-auto mt-4 border border-secondary rounded p-3" id="question-preview-group"> {% comment %} 问题描述预览区域 {% endcomment %}
                         <h5>问题描述预览</h3>
                         <span id="preview-question">(编辑内容时会自动更新预览)</span>
                    </div>
                </div>
                <div class="row align-items-stretch"> {% comment %} 解答过程行，包含编辑器和预览 {% endcomment %}
                    <div class="form-group col-md-7" id="answer-group"> {% comment %} 解答过程编辑器 {% endcomment %}
                        <label for="answer">解答过程 <span class="text-danger">*</span></label>
                        <textarea class="form-control ckeditor {% if form.answer.errors %}is-invalid{% endif %}" id="answer" name="answer" rows="4" required>{{ form.answer.value|default:'' }}</textarea>
                        {% if form.answer.errors %}
                        <div class="error-feedback">{{ form.answer.errors }}</div>
                        {% endif %}
                         <div id="answer-upload" class="mt-3"> {% comment %} 解答图片上传区域 {% endcomment %}
                            <label class="btn btn-outline-secondary btn-sm" for="answer-image-upload">
                                <i class="bi bi-upload me-1"></i> 上传图片 
                            </label>
                            <label class="btn btn-outline-secondary btn-sm" for="answer-image-analysis">
                                <i class="bi bi-upload me-1"></i> 用豆包获取内容 
                            </label>

                            <span id="answer-image-progress"></span> {% comment %} 上传进度显示 {% endcomment %}
                            <input type="file" id="answer-image-upload" name="answer_image" accept="image/*" class="d-none"> {% comment %} 隐藏的文件上传控件 {% endcomment %}
                            <div id="answer-image-preview" class="mt-2"></div> {% comment %} 图片预览区域 {% endcomment %}
                        </div>
                    </div>
                    <div class="form-group col-md-5 ms-auto mt-4 border border-secondary rounded p-3" id="answer-preview-group"> {% comment %} 解答过程预览区域 {% endcomment %}
                        <h5>解答过程预览</h5>
                        <div id="preview-answer">(编辑内容时会自动更新预览)</div>
                    </div>
                </div>
                <div class="mt-4 d-flex justify-content-between"> {% comment %} 按钮区域 {% endcomment %}
                    <button type="submit" id="save-btn" class="btn btn-primary px-6 py-2 font-medium">
                        <i class="bi bi-save me-2"></i> {% if is_update %}更新错题{% else %}保存错题{% endif %}
                    </button>
                    <a href="{% url 'core:subject_chapter_knowledge' CURRENT_SUBJECT_ID %}" class="btn btn-outline-secondary px-6 py-2 font-medium">
                        <i class="bi bi-arrow-left me-2"></i> 返回列表
                    </a>
                </div>
            </form>
        </div>
    </div>
</div>
</form>

<!-- 引入外部JavaScript文件 -->
<script src="{% static 'js/mistake/image_handler.js' %}"></script> {% comment %} 图片处理相关功能 {% endcomment %}
<script src="{% static 'js/mistake/mathjax_editor.js' %}"></script> {% comment %} MathJax和CKEditor联动配置 {% endcomment %}


<script>
// API服务和事件监听
$(document).ready(function() {
    // API服务
    const apiService = {
        loadChapters: (subjectId) => {
            return new Promise((resolve, reject) => {
                if (!subjectId) {
                    resolve([]);
                    return;
                }
                $.getJSON("{% url 'core:ajax_chapters' %}", { subject_id: subjectId })
                    .done(data => resolve(data))
                    .fail((jqXHR) => {
                        const errorMsg = jqXHR.responseJSON?.error || '章节加载失败，请重试';
                        showErrorAlert(errorMsg);
                        reject(errorMsg);
                    });
            });
        },

        loadKnowledgePoints: (chapterId) => {
            return new Promise((resolve, reject) => {
                if (!chapterId) {
                    resolve([]);
                    return;
                }
                $.getJSON("{% url 'core:ajax_knowledge_points' %}", { chapter_id: chapterId })
                    .done(data => resolve(data))
                    .fail((jqXHR) => {
                        const errorMsg = jqXHR.responseJSON?.error || '知识点加载失败，请重试';
                        showErrorAlert(errorMsg);
                        reject(errorMsg);
                    });
            });
        }
    };

    // 工具函数
    const utils = {
        populateSelect: (selectId, data, defaultValue = '') => {
            const $select = $(`#${selectId}`);
            const placeholder = selectId === 'subject' ? '选择学科' : selectId === 'chapter' ? '选择章节' : '选择知识点';
            $select.empty().append(`<option value="${placeholder}</option>`);
            data.forEach(item => {
                const selected = item.id == defaultValue ? 'selected' : '';
                $select.append(`<option value="${item.id}" ${selected}>${item.name}</option>`);
            });
            $select.prop('disabled', data.length === 0);
        },

        showErrorAlert: (message) => {
            const alertDiv = $('<div class="alert alert-danger alert-dismissible fade show" role="alert">')
                .text(message)
                .append('<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>');
            $('.card-body').prepend(alertDiv);
            setTimeout(() => alertDiv.alert('close'), 3000);
        }
    };

    // 事件监听
    const setupEventListeners = () => {
        // 学科选择变化
        $('#subject').change(async function() {
            const subjectId = $(this).val();
            const $chapter = $('#chapter');
            const $knowledgePoint = $('#knowledge_point');

            $chapter.prop('disabled', true).empty().append('<option value="">加载中...</option>');
            $knowledgePoint.prop('disabled', true).empty().append('<option value="">请先选择章节</option>');

            try {
                const chapters = await apiService.loadChapters(subjectId);
                utils.populateSelect('chapter', chapters, {{ initial_chapter.id|default:'null' }});
                // 如果有初始章节ID，自动加载知识点
                if ({{ initial_chapter.id|default:'null' }}) {
                    setTimeout(async () => {
                        const knowledgePoints = await apiService.loadKnowledgePoints({{ initial_chapter.id }});
                        utils.populateSelect('knowledge_point', knowledgePoints, {{ initial_knowledge_point.id|default:'null' }});
                    }, 500);
                }
            } catch (error) {
                console.error('学科变更处理失败:', error);
                $chapter.empty().append('<option value="">选择章节</option>');
            }
        });

        // 章节选择变化
        $('#chapter').change(async function() {
            const chapterId = $(this).val();
            const $knowledgePoint = $('#knowledge_point');

            $knowledgePoint.prop('disabled', true).empty().append('<option value="">加载中...</option>');

            try {
                const knowledgePoints = await apiService.loadKnowledgePoints(chapterId);
                utils.populateSelect('knowledge_point', knowledgePoints);
            } catch (error) {
                console.error('章节变更处理失败:', error);
                $knowledgePoint.empty().append('<option value="">选择知识点</option>');
            }
        });
    };

    // 初始化页面数据
    const initPageData = () => {
        // 如果有初始学科，触发学科选择事件
        {% if initial_subject %}
            $('#subject').trigger('change');
        {% endif %}
    };

    // 初始化
    setupEventListeners();
    initPageData();
});
</script>
{% endblock %}

